package org.fuys.coder.domain.auth.service.handler.login;

import lombok.extern.slf4j.Slf4j;
import org.fuys.coder.common.entity.Pair;
import org.fuys.coder.common.exception.BusinessException;
import org.fuys.coder.common.exception.handler.NeedCallBackException;
import org.fuys.coder.domain.auth.model.req.LoginReq;
import org.fuys.coder.domain.auth.model.vo.UserVo;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.auth.service.handler.login
 * @className: LoginHandlerChain
 * @author: WangJing
 * @description: 登录处理器链路
 * @date: 2024/8/9 17:23
 * @version: 1.0
 */
@Slf4j
public class LoginHandlerChain {

    private List<LoginHandler> handlerList=new ArrayList<>();

    public void addHandler(LoginHandler handler){
        handlerList.add(handler);
    }

    public void removeHandler(LoginHandler loginHandler){
        handlerList.remove(loginHandler);
    }

    public Pair<Integer, UserVo> doHandle(LoginReq req){
        try{
            Pair<Integer,UserVo> result=null;
            for (LoginHandler loginHandler : handlerList) {
                final Pair<Integer, UserVo> handle = loginHandler.handle(req);
                if(!ObjectUtils.isEmpty(handle)){
                    if(handle.getLeft().equals(-1)){
                        return handle;
                    }else{
                        result=handle;
                        break;
                    }
                }
            }
            return result;
        }catch (BusinessException e){
            log.error("登录链路中存在异常 信息:"+e.getMsg());
            throw new NeedCallBackException(e.getMsg());
        }
    }
}
